#include "online_users.h"
#include <stdlib.h>
#include <string.h>

OnlineUser* g_online_users = NULL;
pthread_mutex_t g_online_users_mutex = PTHREAD_MUTEX_INITIALIZER;

void online_users_init(void) {
    pthread_mutex_init(&g_online_users_mutex, NULL);
}

void online_users_clear(void) {
    pthread_mutex_lock(&g_online_users_mutex);
    OnlineUser* current = g_online_users;
    while (current) {
        OnlineUser* temp = current;
        current = current->next;
        free((void*)temp->nickname); // 释放昵称内存
        free(temp);
    }
    g_online_users = NULL;
    pthread_mutex_unlock(&g_online_users_mutex);
}

void online_users_add(uint32_t user_id, const char* nickname) {
    if (!nickname) return;
    
    pthread_mutex_lock(&g_online_users_mutex);
    
    // 检查用户是否已存在
    OnlineUser* existing = g_online_users;
    while (existing) {
        if (existing->user_id == user_id) {
            // 更新昵称
            free((void*)existing->nickname);
            existing->nickname = strdup(nickname);
            pthread_mutex_unlock(&g_online_users_mutex);
            return;
        }
        existing = existing->next;
    }
    
    // 添加新用户
    OnlineUser* new_user = (OnlineUser*)malloc(sizeof(OnlineUser));
    new_user->user_id = user_id;
    new_user->nickname = strdup(nickname);
    new_user->next = g_online_users;
    g_online_users = new_user;
    
    pthread_mutex_unlock(&g_online_users_mutex);
}

void online_users_remove(uint32_t user_id) {
    pthread_mutex_lock(&g_online_users_mutex);
    
    OnlineUser* prev = NULL;
    OnlineUser* current = g_online_users;
    
    while (current) {
        if (current->user_id == user_id) {
            if (prev) {
                prev->next = current->next;
            } else {
                g_online_users = current->next;
            }
            free((void*)current->nickname);
            free(current);
            break;
        }
        prev = current;
        current = current->next;
    }
    
    pthread_mutex_unlock(&g_online_users_mutex);
}

void online_users_destroy(void) {
    online_users_clear();
    pthread_mutex_destroy(&g_online_users_mutex);
}